#include <winsock2.h>
#include <ballade/util/func.h>
#include <ballade/network/output_stream.h>

namespace Ballade
{
	namespace Network
	{
		
		// Constructor/Deconstructor
		OutputStream::OutputStream() {}
		
		OutputStream::OutputStream(const int sock)
		{
			_sock = sock;
		}
		
		OutputStream::~OutputStream()
		{
			Logger_.close();
		}
		// End of Constructor/Deconstructor
		
		// Public
		const int OutputStream::write(char *buf, const int len) const
		{
			int slen = send(_sock, buf, len, 0);
			
			int error = WSAGetLastError();
			if(slen == 0 ||
				error == WSAECONNRESET || 
				error == WSAENOTCONN)
			{
				throw SocketError("Send data failed");
			}
			
			if(Logger_.isDebugEnabled())
			{
				char *buf_ = new char[slen*12];
				memset(buf_, 0x00, slen*12);
				Util::repr(buf_, buf, slen);
				Logger_.debug("OutputStream(Write) - Bytes sent: %d, Raw data: %s", slen, buf_);
				delete [] buf_;
			}
			return slen;
		}
		// End of Public
		
		// Static
		Util::Logger &OutputStream::Logger_ = Util::Logger::getInstance();
		// End of Static

	}
}